using AngleSharp;
using AngleSharp.Dom;
using Viyi.Strings.Extensions;
using Viyi.Util.Extensions;

namespace JamesFan.FetchAreaCodes.Parser;

abstract class ContentParser : IParser {
    protected ContentParser(CodeEntry baseEntry, string content) {
        Content = content;
        BaseEntry = baseEntry;
    }

    protected string Content { get; }
    protected CodeEntry BaseEntry { get; }
    protected Uri BaseUri => BaseEntry.Uri!;
    protected string ParentCode => BaseEntry.ParentId;

    public List<Uri> Links { get; } = new();
    public List<CodeEntry> Entries { get; } = new();

    public virtual async Task ParseAsync() {
        IBrowsingContext context = BrowsingContext.New();
        using IDocument document = await context.OpenAsync(req => req.Content(Content));
        ProcessDocument(document);
    }

    protected abstract void ProcessDocument(IDocument document);

    protected virtual IElement? FindTheTable(IDocument document) {
        return document.QuerySelectorAll("table").LastOrDefault(el => el.ClassList?.Length > 0);
    }

    protected CodeEntry? AddEntry(string? code, string? name, string? link) {
        return (code.IsEmpty() || name.IsEmpty())
            .Then(
                () => (CodeEntry?)null,
                () => new CodeEntry(BaseEntry, code!, name!, link).Also(Entries.Add)
            );
    }
}
